package com.ygqh.baby.controller.mobile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.model.*;
import com.ygqh.baby.po.YgCouponDetail;
import com.ygqh.baby.po.YgPublish;
import com.ygqh.baby.po.YgSku;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.*;
import com.ygqh.baby.service.impl.DocumentConstant;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.ExceptionUtil;
import com.ygqh.baby.utils.SessionUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.*;

/**
 * 优惠卷
 *
 * @author guohao
 */
@Controller
@RequestMapping("/mobile/coupon")
public class YgCouponController extends BaseController {

    @Autowired
    private YgCouponService couponService;
    @Autowired
    private YgOrderService orderService;
    @Autowired
    private YgUserService ygUserService;
    @Autowired
    private YgShoppingCarService ygShoppingCarService;
    @Autowired
    private YgPublishService ygPublishService;
    @Autowired
    private YgCouponDetailService couponDetailService;
    @Autowired
    private YgBmdismService ygBmdismService;
    @Autowired
    private YgSkuService skuService;
    @Autowired
    private DocumentConstant documentConstant;
    @Autowired
    private RedisDao redisDao;
    private String DISABLE_COUPON_KEY = "disablecoupon";
    @Autowired
    private WxMpMessageService wxMpMessageService;
    private final SalesPlatform salesPlatform = SalesPlatform.Yiigoo;

    /**
     * 获取优惠卷 及满减金额，运费的接口
     *
     * @param couponDetailId
     * @param productPrice
     * @param callback
     * @return
     */
    @Deprecated
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "findCouponForPayOld", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject findCouponForPay(Long couponDetailId, BigDecimal productPrice, String formId, String callback) {
        JSONPObject json;
        if (couponDetailId == -1L) {
            couponDetailId = null;
        }
        YgUser user = SessionUtil.getCurrentUser();

        Boolean isNewCustom = ygUserService.isNewCustom(user.getId());

        Map<String, Object> map = new HashMap<>();
        List<YgShoppingCarModel> carList = ygShoppingCarService.findIsCheck(user.getId());
        // 获取新客和自选包优惠金额
        BigDecimal packDisPrice;
        BigDecimal newCustomDisPrice;
        // 特例品金额
        BigDecimal specialPrice = zero;
        // 多买多折优惠
        BigDecimal bmdis = zero;
        ygShoppingCarService.doNewCusBussness(carList);

        ygBmdismService.getBestBmdism(carList);

        for (YgShoppingCarModel car : carList) {
            BigDecimal salesPrice = car.getRealSalesPrice();
            if (car.getIsSpecial()) {
                if (isNewCustom && car.getNewCustomPrice().compareTo(zero) > 0) {
                    specialPrice = specialPrice.add(salesPrice.multiply(new BigDecimal(car.getQuantity() - 1)));
                    specialPrice = specialPrice.add(car.getNewCustomPrice());
                } else {
                    specialPrice = specialPrice.add(salesPrice.multiply(new BigDecimal(car.getQuantity())));
                }

            }
            if (car.getSalesType().equals(PromotionType.Bmdism)) {
                BigDecimal dis = (salesPrice.subtract(car.getPromotionPrice())).multiply(new BigDecimal(car.getQuantity().toString()));
                bmdis = bmdis.add(dis);
            }
        }
        Message result = orderService.getNewCusAndPackPrice(carList, user.getId(), false);
        BigDecimal packDisPriceWithSpecial;
        if (result.getType().equals(Message.Type.success)) {
            Map<String, BigDecimal> extra = (Map<String, BigDecimal>) result.getExtra();
            packDisPrice = extra.get("packDisPrice");
            newCustomDisPrice = extra.get("newCustomDisPrice");
            packDisPriceWithSpecial = extra.get("packDisPriceWithSpecial");
        } else {
            return new JSONPObject(callback, result);
        }
        newCustomDisPrice = newCustomDisPrice.add(bmdis);
        // 获取满减金额
        BigDecimal realPrice = productPrice.subtract(newCustomDisPrice).subtract(packDisPrice);

        BigDecimal couponPrice = zero;
        YgCouponModel model = null;

        // 验证优惠券禁用设置
        if (!validateDisableCouponFromRedis()) {
            // 自选包设置为特例品导致特例品金额多减,在给加回来。
            BigDecimal subtract = realPrice.subtract(specialPrice).add(packDisPriceWithSpecial);
            if (subtract.compareTo(zero) > 0) {
                model = couponService.findCouponForPayV2(user.getId(), couponDetailId, subtract, false, carList, salesPlatform);

                couponPrice = model != null ? model.getFaceValue() : couponPrice;
            }
        }
        // 该满减是否活动是否可以使用优惠卷
        Map<String, Object> manJian = orderService.getManJianPrice(realPrice.subtract(couponPrice), formId, user.getId());
        Boolean useCoupon = (Boolean) manJian.get("useCoupon");
        BigDecimal manJianPrice = (BigDecimal) manJian.get("manjianPrice");

        if (!useCoupon) {
            manJianPrice = zero;
        }
        BigDecimal expressPrice = zero;
        if (model != null) {
            // 当商品金额-新客及自选包优惠金额 - 满减金额 -优惠券金额 < 0
            BigDecimal price4exp = realPrice.subtract(manJianPrice).subtract(model.getFaceValue());
            if (price4exp.compareTo(zero) < 0) {
                price4exp = zero;
            }
            expressPrice = orderService.getExpressPrice(price4exp, user.getId());
        } else {
            expressPrice = orderService.getExpressPrice(realPrice.subtract(manJianPrice), user.getId());
        }

        map.put("coupon", model);
        map.put("packDisPrice", packDisPrice);
        map.put("newCustomDisPrice", newCustomDisPrice);
        map.put("expressPrice", expressPrice.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        map.put("manJianPrice", manJianPrice.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, map));
        return json;
    }

    /**
     * 验证优惠券禁用设置 true--已设置并处于进行中， false--无效
     *
     * @return
     */
    @SuppressWarnings("rawtypes")
    private boolean validateDisableCouponFromRedis() {
        try {
            String couponInfo = redisDao.get(DISABLE_COUPON_KEY);
            Map map = JSON.parseObject(couponInfo, Map.class);
            if (MapUtils.isEmpty(map)) {
                return false;
            }
            Long currentTime = new Date().getTime();
            String startDate = map.get("startDate").toString();
            String endDate = map.get("endDate").toString();
            String format = "yyyy-MM-dd HH:mm:ss";
            Long startTime = DateConvertUtils.parse(startDate + " 00:00:00", format).getTime();
            Long endTime = DateConvertUtils.parse(endDate + " 23:59:59", format).getTime();
            if (startTime.compareTo(currentTime) > 0 || endTime.compareTo(currentTime) < 0) {
                return false;
            }
        } catch (Exception e) {
            logger.error("验证优惠券禁用设置异常，" + ExceptionUtil.getExceptionMsg(e));
            return false;
        }
        return true;
    }

    /**
     * 获取优惠卷 及满减金额，运费的接口
     *
     * @param couponDetailId
     * @param productPrice
     * @param callback
     * @return
     */
    @RequestMapping(value = "findCouponForPayPt", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject findCouponForPayPt(@RequestParam(defaultValue = "false") Boolean distribution,String skuInfos,
                                          Long couponDetailId, BigDecimal productPrice, String formId, String callback) {
        JSONPObject json = null;
        YgUser user = SessionUtil.getCurrentUser();

        List<YgPtSkuInfo> skuList = JSON.parseObject(skuInfos, new TypeReference<List<YgPtSkuInfo>>() {
        });
        Map<String, Object> map = new HashMap<String, Object>();
        if (couponDetailId == null || couponDetailId == -1l) {
            couponDetailId = null;
        }
        List<YgShoppingCarModel> carList = ygShoppingCarService.findItemInfoPt(skuList, user.getId(),distribution);
        BigDecimal ptPrice = new BigDecimal("0");// 拼团商品金额
        for (YgShoppingCarModel car : carList) {
            ptPrice = ptPrice.add(car.getRealSalesPrice().multiply(new BigDecimal(car.getQuantity())));
        }

        // 获取满减金额
        BigDecimal realPrice = ptPrice;

        Map<String, Object> manJian = orderService.getManJianPrice(realPrice, formId, user.getId());
        BigDecimal manJianPrice = (BigDecimal) manJian.get("manjianPrice");

        map.put("coupon", null);
        map.put("packDisPrice", new BigDecimal("0.00"));
        map.put("goupDisPrice", productPrice.subtract(ptPrice));
        map.put("newCustomDisPrice", new BigDecimal("0.00"));
        map.put("expressPrice", new BigDecimal("0.00"));
        map.put("manJianPrice", manJianPrice);
        json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, map));
        return json;
    }

    /**
     * 结算页 获取优惠卷列表
     *
     * @param cStatus
     * @param productPrice
     * @param callback
     * @return
     */
    @Deprecated
    @SuppressWarnings({"unchecked"})
    @RequestMapping(value = "findCouponListForPayOld", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject findCouponListForPay(@RequestParam CouponStatus cStatus, @RequestParam BigDecimal productPrice,
                                            @RequestParam BigDecimal specialPrice, String productIds, String formId,
                                            @RequestParam String callback, Boolean filterJiajiaGou) {
        JSONPObject json;
        YgUser user = SessionUtil.getCurrentUser();
        Map<String, Object> manJian = orderService.getManJianPrice(productPrice, formId, user.getId());
        Boolean useCoupon = (Boolean) manJian.get("useCoupon");
        BigDecimal manJianPrice = (BigDecimal) manJian.get("manjianPrice");

        if (!useCoupon && cStatus.equals(CouponStatus.Usable)) {
            json = new JSONPObject(callback, Message.success(documentConstant.COUPON_IS_EMPTY, null));
        } else {
            BigDecimal subtract = productPrice.subtract(manJianPrice).subtract(specialPrice);
            if (subtract.compareTo(new BigDecimal(0)) < 0) {
                subtract = new BigDecimal(0);
            }
            List<YgShoppingCarModel> carList;
            if (filterJiajiaGou != null && !filterJiajiaGou) {
                // 过滤加价购商品（即不进购物车，直接选择商品结算）
                carList = getCarList(productIds, user.getId());
            } else { // 考虑区分加价够商品(即购物车结算商品)
                carList = ygShoppingCarService.findIsCheck(user.getId());
            }

            // 自选包设置为特例品导致特例品金额多减,在给加回来。
            Message packMsg = orderService.getNewCusAndPackPrice(carList, user.getId(), false);
            if (!Message.isSuccess(packMsg)) {
                return new JSONPObject(callback, packMsg);
            }
            Map<String, BigDecimal> extra = (Map<String, BigDecimal>) packMsg.getExtra();
            BigDecimal packDisPriceWithSpecial = extra.get("packDisPriceWithSpecial");
            subtract = subtract.add(packDisPriceWithSpecial);
            Boolean onlySpecial = false;
            if (subtract.compareTo(zero) < 0) {
                subtract = zero;
                onlySpecial = true;
            }
            if (onlySpecial && cStatus.equals(CouponStatus.Usable)) {
                json = new JSONPObject(callback, Message.success(documentConstant.COUPON_IS_EMPTY, null));
            } else {
                List<YgCouponModel> model = couponService.findCouponListForPayV2(user.getId(), null, subtract, cStatus, useCoupon, onlySpecial, carList,
                        salesPlatform);
                json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, model));
            }
        }
        return json;
    }

    private List<YgShoppingCarModel> getCarList(String productIds, Long userId) {
        List<BaseSkuInfo> skuInfoList = new ArrayList<>();
        for (String string : productIds.split(",")) {
            String productId = string.trim();
            if (StringUtils.isBlank(productId)) {
                continue;
            }
            List<YgSku> skuList = skuService.find(Long.valueOf(productId));
            if (CollectionUtils.isEmpty(skuList)) {
                continue;
            }
            skuInfoList.add(new BaseSkuInfo(skuList.get(0).getId(), 1L));
        }
        if (CollectionUtils.isEmpty(skuInfoList)) {
            return new ArrayList<>();
        }
        return ygShoppingCarService.findItemInfo(skuInfoList, userId, PromotionType.Ordinary);
    }

    /**
     * 个人中心获取优惠卷列表
     *
     * @param cStatus
     * @param callback
     * @return
     */
    @RequestMapping(value = "findOwnCouponList", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject findOwnCouponList(QueryInfo queryInfo, CouponStatus cStatus, SceneType sceneType, String callback) {
        JSONPObject json = null;
        YgUser user = SessionUtil.getCurrentUser();
        List<YgCouponModel> couponList = couponService.findOwnCouponList(queryInfo, user.getId(), cStatus, sceneType, salesPlatform);
        json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, couponList));
        return json;
    }

    /**
     * 绑定优惠卷
     *
     * @param couponCode
     * @param callback
     * @return
     */
    @RequestMapping(value = "bindCoupon", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject bindCoupon(@RequestParam(required = true) String couponCode, String callback) {
        YgUser user = SessionUtil.getCurrentUser();
        Message msg = couponService.bindCoupon(couponCode, user);

        return new JSONPObject(callback, msg);
    }

    /**
     * 领取优惠卷
     *
     * @param couponBatchId
     * @param callback
     * @return
     */
    @RequestMapping(value = "receiveCoupon", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject receiveCoupon(@RequestParam(required = true) Long couponBatchId, String callback) {
        YgUser user = SessionUtil.getCurrentUser();
        Message msg = couponService.receiveCoupon(couponBatchId, user);
        if (Message.isSuccess(msg)) {
            YgCouponDetail detail = (YgCouponDetail) msg.getExtra();
            new Thread(new Runnable() {

                @Override
                public void run() {
                    YgUser ygUser = ygUserService.findById(user.getId());
                    wxMpMessageService.sendCouponMsg("您有" + detail.getFaceValue().setScale(0) + "元优惠券已到账", "/user/coupon.html", ygUser,
                            detail.getFaceValue().setScale(0) + "元优惠券", DateConvertUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"), "请到【我的】->【优惠券】界面查询");
                }
            }).start();
            msg.setExtra(null);
        }
        return new JSONPObject(callback, msg);
    }

    /**
     * 领取优惠卷（支持多个）
     *
     * @param couponBatchIds
     * @param callback
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "receiveCouponBatch", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject receiveCouponBatch(@RequestParam(required = true) String couponBatchIds, String callback) {
        YgUser user = SessionUtil.getCurrentUser();
        Message msg = couponService.receiveCouponBatch(couponBatchIds, user);
        if (Message.isSuccess(msg)) {
            List<YgCouponDetail> detailList = (List<YgCouponDetail>) msg.getExtra();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Date endDate = null;
                    StringBuffer sb = new StringBuffer();
                    for (YgCouponDetail detail : detailList) {
                        if (endDate == null || endDate.before(detail.getEndDate())) {
                            endDate = detail.getEndDate();
                        }
                        if (sb.length() > 0) {
                            sb.append("、");
                        }
                        sb.append(detail.getFaceValue().setScale(0)).append("元");
                    }
                    YgUser ygUser = ygUserService.findById(user.getId());
                    wxMpMessageService.sendCouponMsg("您有" + sb.toString() + "元优惠券已到账", "/user/coupon.html", ygUser, sb.toString() + "元优惠券",
                            DateConvertUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"), "请到【我的】->【优惠券】界面查询");
                }
            }).start();
            msg.setExtra(null);
        }
        return new JSONPObject(callback, msg);
    }

    /**
     * 领取优惠卷（支持多个）
     *
     * @param couponBatchIds
     * @param callback
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "receiveCouponBatchV2", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject receiveCouponBatchV2(@RequestParam(required = true) String couponBatchIds, Date endDate, String callback) {
        endDate = DateConvertUtils.parse("2017-10-30", DateConvertUtils.DATE_FORMAT);
        YgUser user = SessionUtil.getCurrentUser();
        Message msg = couponService.receiveCouponBatchV2(couponBatchIds, endDate, user);
        if (Message.isSuccess(msg)) {
            List<YgCouponDetail> detailList = (List<YgCouponDetail>) msg.getExtra();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Date endDate = null;
                    StringBuffer sb = new StringBuffer();
                    for (YgCouponDetail detail : detailList) {
                        if (endDate == null || endDate.before(detail.getEndDate())) {
                            endDate = detail.getEndDate();
                        }
                        if (sb.length() > 0) {
                            sb.append("、");
                        }
                        sb.append(detail.getFaceValue().setScale(0)).append("元");
                    }
                    YgUser ygUser = ygUserService.findById(user.getId());
                    wxMpMessageService.sendCouponMsg("您有" + sb.toString() + "元优惠券已到账", "/user/coupon.html", ygUser, sb.toString() + "元优惠券",
                            DateConvertUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"), "请到【我的】->【优惠券】界面查询");
                }
            }).start();
            msg.setExtra(null);
        }
        return new JSONPObject(callback, msg);
    }

    /**
     * 分享晒单领取优惠卷
     *
     * @param couponBatchId
     * @param publishId
     * @param callback
     * @return
     */
    @RequestMapping(value = "receiveCoupon4Publish", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject receiveCoupon4Publish(@RequestParam(required = true) Long couponBatchId, @RequestParam(required = true) Long publishId,
                                             String callback) {
        YgUser user = SessionUtil.getCurrentUser();
        YgPublish publish = ygPublishService.findById(publishId);
        Message msg = null;
        // 只有第一次分享自己的晒单才可以领取优惠卷
        if (publish != null && publish.getUserId().equals(user.getId()) && !publish.getIsReceiveCoupon()) {
            msg = couponDetailService.receiveIncreateCoupon(couponBatchId, user);
            if (msg.getType().equals(Message.Type.success)) {
                // 领取后更新晒单
                publish.setIsReceiveCoupon(true);
                ygPublishService.update(publish);
            }
        }

        return new JSONPObject(callback, msg);
    }

    /**
     * 获取商品优惠券下的商品列表
     *
     * @param id
     * @param callback
     * @return
     */
    @RequestMapping(value = "findProductListByCouponId", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject findProductListByCouponId(@RequestParam(required = true) Long id, String callback) {
        ResultSet<YgProduct4ListModel> result = couponService.findProductListByCouponId(id);
        return new JSONPObject(callback, Message.success(result.getResult()));
    }

    /**
     * 获取优惠（立即购买）
     *
     * @param couponDetailId
     * @param productPrice
     * @param formId
     * @param callback
     * @param skuInfos
     * @return
     */
    @RequestMapping(value = "findCouponForPayNow", method = RequestMethod.GET)
    public String findCouponForPayNow(Long couponDetailId, BigDecimal productPrice, String formId, String callback, String skuInfos) {
        return skuService.checkSkuInfoIsGroup(skuInfos) ? "forward:/mobile/coupon/findCouponForPayPt.do" : "forward:/mobile/coupon/findCouponWithSkuInfo.do";
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(value = "findCouponWithSkuInfo", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject findCouponWithSkuInfo(Long couponDetailId, BigDecimal productPrice, String formId, String callback, String skuInfos) {
        if (couponDetailId == -1) {
            couponDetailId = null;
        }
        List<BaseSkuInfo> skuList = JSON.parseObject(skuInfos, new TypeReference<List<BaseSkuInfo>>() {
        });
        YgUser user = SessionUtil.getCurrentUser();
        List<YgShoppingCarModel> carList = ygShoppingCarService.findItemInfo(skuList, user.getId(), PromotionType.Ordinary);

        ygShoppingCarService.doNewCusBussness(carList);// 只有一件享受新客价

        ygBmdismService.getBestBmdism(carList);

        Boolean isNewCustom = ygUserService.isNewCustom(user.getId());

        Map<String, Object> map = new HashMap<String, Object>();
        // 获取新客和自选包优惠金额
        BigDecimal packDisPrice = zero;
        BigDecimal newCustomDisPrice = zero;
        BigDecimal specialPrice = zero;// 特例品金额
        BigDecimal bmdis = zero;// 多买多折优惠

        for (YgShoppingCarModel car : carList) {
            BigDecimal salesPrice = car.getRealSalesPrice();
            if (car.getIsSpecial()) {
                if (isNewCustom && car.getNewCustomPrice().compareTo(zero) > 0) {
                    specialPrice = specialPrice.add(salesPrice.multiply(new BigDecimal(car.getQuantity() - 1)));
                    specialPrice = specialPrice.add(car.getNewCustomPrice());
                } else {
                    specialPrice = specialPrice.add(salesPrice.multiply(new BigDecimal(car.getQuantity())));
                }
            }
            if (car.getSalesType().equals(PromotionType.Bmdism)) {
                BigDecimal dis = (salesPrice.subtract(car.getPromotionPrice())).multiply(new BigDecimal(car.getQuantity().toString()));
                bmdis = bmdis.add(dis);
            }
        }
        Message result = orderService.getNewCusAndPackPrice(carList, user.getId(), false);
        BigDecimal packDisPriceWithSpecial;
        if (result.getType().equals(Message.Type.success)) {
            Map<String, BigDecimal> extra = (Map<String, BigDecimal>) result.getExtra();
            packDisPrice = extra.get("packDisPrice");
            newCustomDisPrice = extra.get("newCustomDisPrice");
            packDisPriceWithSpecial = extra.get("packDisPriceWithSpecial");
        } else {
            return new JSONPObject(callback, result);
        }
        newCustomDisPrice = newCustomDisPrice.add(bmdis);
        // 获取满减金额
        BigDecimal realPrice = productPrice.subtract(newCustomDisPrice).subtract(packDisPrice);

        BigDecimal couponPrice = zero;
        YgCouponModel model = null;

        // 验证优惠券禁用设置
        if (!validateDisableCouponFromRedis()) {
            Boolean onlySpecial = false;
            if (realPrice.subtract(specialPrice).compareTo(zero) <= 0) {
                onlySpecial = true;
            }
            if (!onlySpecial) {
                BigDecimal subtract = realPrice.subtract(specialPrice).add(packDisPriceWithSpecial);
                if (subtract.compareTo(zero) < 0) {
                    subtract = zero;
                }
                model = couponService.findCouponForPayV2(user.getId(), couponDetailId, subtract, onlySpecial, carList, salesPlatform);
                couponPrice = model != null ? model.getFaceValue() : couponPrice;
            }
        }
        // 该满减是否活动是否可以使用优惠卷
        Map<String, Object> manJian = orderService.getManJianPrice(realPrice.subtract(couponPrice), formId, user.getId());
        Boolean useCoupon = (Boolean) manJian.get("useCoupon");
        BigDecimal manJianPrice = (BigDecimal) manJian.get("manjianPrice");
        if (!useCoupon) {
            manJianPrice = zero;
        }
        BigDecimal expressPrice = zero;
        if (model != null) {
            // 当商品金额-新客及自选包优惠金额 - 满减金额 -优惠券金额 < 0
            BigDecimal price4exp = realPrice.subtract(manJianPrice).subtract(model.getFaceValue());
            if (price4exp.compareTo(zero) < 0) {
                price4exp = zero;
            }
            expressPrice = orderService.getExpressPrice(price4exp, user.getId());
        } else {
            expressPrice = orderService.getExpressPrice(realPrice.subtract(manJianPrice), user.getId());
        }
        map.put("coupon", model);
        map.put("packDisPrice", packDisPrice);
        map.put("newCustomDisPrice", newCustomDisPrice);
        map.put("expressPrice", expressPrice.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        map.put("manJianPrice", manJianPrice.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        return new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, map));
    }

    /**
     * 获取优惠券信息
     *
     * @param couponId
     * @param callback
     * @return
     */
    @RequestMapping(value = "findCouponInfoById", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject findCouponInfoById(@RequestParam Long couponId, String callback) {
        return new JSONPObject(callback, Message.success(couponService.findById(couponId)));
    }


}
